package view;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;

/**
 * Class to use a JFileChooser when the connected button is pressed.
 * @author Sarah George
 * @version Autumn 2012
 */
@SuppressWarnings("serial")
public class BrowseAction extends AbstractAction {
	
	/**
	 * Field to hold the JFileChooser.
	 */
	private JFileChooser my_chooser;
	
	/**
	 * Field that holds the JFrame. Needed to render the instance of a JFileChooser.
	 */
	private JFrame my_frame;
	
	/**
	 * Field to hold the text field that holds the file path.
	 */
	private JTextField my_fp;
	
	/**
	 * Constructor for a browse action.
	 * @param the_frame The JFrame over which the JFileChooser will display.
	 * @param the_chooser The JFileChooser.
	 * @param the_pf The JTextField that holds the file path.
	 */
	public BrowseAction(JFrame the_frame, JFileChooser the_chooser, JTextField the_pf) {
		super("Browse...");
		putValue(Action.MNEMONIC_KEY, KeyEvent.VK_B);
		putValue(Action.SELECTED_KEY, true);
		my_chooser = the_chooser;
		my_frame = the_frame;
		my_fp = the_pf;
	}

	/**
	 * Method to browse for a file and if a file is chosen, set the text of the 
	 * text field to be the file path.
	 * @param arg0 the action event that triggers the method.
	 */
	@Override
	public void actionPerformed(ActionEvent arg0) {
		int returnVal = my_chooser.showOpenDialog(my_frame);
		
		if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = my_chooser.getSelectedFile();
            String file_path = file.getAbsolutePath();
            my_fp.setText(file_path);
		} else {
            //Open canceled by user
        }
	}
}//End class Browse Action.